//
//  YQRecordVideoVC.m
//  Youqun
//
//  Created by 王崇磊 on 16/5/16.
//  Copyright © 2016年 W_C__L. All rights reserved.
//
// 用户面签

#import "SJUserFaceSignRecordVideoVc.h"
#import "WCLRecordEngine.h"
#import "WCLRecordProgressView.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import "MBProgressHUD+Add.h"
typedef NS_ENUM(NSUInteger, UploadVieoStyle) {
    VideoRecord = 0,
    VideoLocation,
};

@interface SJUserFaceSignRecordVideoVc ()<WCLRecordEngineDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *flashLightBT;
@property (weak, nonatomic) IBOutlet UIButton *changeCameraBT;
@property (weak, nonatomic) IBOutlet UIButton *recordNextBT;
@property (weak, nonatomic) IBOutlet UIButton *recordBt;
@property (weak, nonatomic) IBOutlet UIButton *locationVideoBT;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewTop;
@property (weak, nonatomic) IBOutlet WCLRecordProgressView *progressView;
@property (strong, nonatomic) WCLRecordEngine         *recordEngine;
@property (assign, nonatomic) BOOL                    allowRecord;//允许录制
@property (assign, nonatomic) UploadVieoStyle         videoStyle;//视频的类型
@property (strong, nonatomic) UIImagePickerController *moviePicker;//视频选择器
@property (strong, nonatomic) MPMoviePlayerViewController *playerVC;
@property (weak, nonatomic) IBOutlet UIView *mainVideoView;
@property (weak, nonatomic) IBOutlet UIImageView *defImageUserBgView;

@end

@implementation SJUserFaceSignRecordVideoVc

- (void)dealloc {
    NSLog(@"dealloc == %@",self);
    _recordEngine = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:[_playerVC moviePlayer]];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.recordEngine shutdown];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (_recordEngine == nil) {
        [self.mainVideoView.layer insertSublayer:[self.recordEngine previewLayer] atIndex:0];
        [self.recordEngine previewLayer].frame = self.mainVideoView.bounds;
    }
    [self.recordEngine startUp];
    [self.recordEngine changeCameraInputDeviceisFront:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // 博客地址：http://blog.csdn.net/wang631106979/article/details/51498009
    self.allowRecord = YES;
}

//根据状态调整view的展示情况
- (void)adjustViewFrame {
    [self.view layoutIfNeeded];
    [UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        if (self.recordBt.selected) {
            self.topViewTop.constant = -64;
            [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        }else {
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
            self.topViewTop.constant = 0;
        }
        if (self.videoStyle == VideoRecord) {
            self.locationVideoBT.alpha = 0;
        }
        [self.view layoutIfNeeded];
    } completion:nil];
}

#pragma mark - set、get方法
- (WCLRecordEngine *)recordEngine {
    if (_recordEngine == nil) {
        _recordEngine = [[WCLRecordEngine alloc] init];
        _recordEngine.delegate = self;
    }
    return _recordEngine;
}

- (UIImagePickerController *)moviePicker {
    if (_moviePicker == nil) {
        _moviePicker = [[UIImagePickerController alloc] init];
        _moviePicker.delegate = self;
        _moviePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _moviePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
    }
    return _moviePicker;
}

#pragma mark - Apple相册选择代理
#pragma mark - 选择了某个照片或视频的回调函数/代理回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [self dismissViewControllerAnimated:YES completion:^{
        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
        //NSLog(@"videoData == %@",videoData);
        CGFloat imgSize=[videoData length]/1000.0;
        NSLog(@"原视频videoURL == %@",videoURL);
        NSLog(@"原视频文件大小 == %fM",imgSize/1000.0);
        //AVFoundation视频转码(MOV转MP4)
        [self convertMovSourceURL:videoURL];
    }];
}
#pragma mark - AVFoundation视频转码(MOV转MP4)
-(void)convertMovSourceURL:(NSURL *)sourceUrl
{
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showMessag:@"MP4转码中" toView:weakSelf.view];
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:sourceUrl options:nil];
    NSArray *compatiblePresets=[AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    //NSLog(@"%@",compatiblePresets);
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession=[[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetHighestQuality];
        NSDateFormatter *formater=[[NSDateFormatter alloc] init];//用时间给文件全名
        [formater setDateFormat:@"yyyyMMddHHmmss"];
        
        NSString *cachesDirectoryPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"VideosMP4"];
        //创建MP4视频存放文件夹
        BOOL isDir = NO;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL existed = [fileManager fileExistsAtPath:cachesDirectoryPath isDirectory:&isDir];
        if ( !isDir&&!existed) {
            [fileManager createDirectoryAtPath:cachesDirectoryPath withIntermediateDirectories:YES attributes:nil error:nil];
        };
        
        //删除之前转码产生的mp4文件
        NSArray *cacheFiles=[fileManager contentsOfDirectoryAtPath:cachesDirectoryPath error:nil];
        for (NSString *fileName in cacheFiles) {
            if([fileName containsString:@".mp4"]){
               [fileManager removeItemAtPath:[cachesDirectoryPath stringByAppendingPathComponent:fileName] error:nil];
            }
        }
        //创建新转码的MP4文件路径
        NSString *cachePath=[cachesDirectoryPath stringByAppendingFormat:@"/SJJOutPutRecordVideo_%@.mp4", [formater stringFromDate:[NSDate date]]];
        NSLog(@"cachePath == %@",cachePath);
        exportSession.outputURL=[NSURL fileURLWithPath:cachePath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        exportSession.shouldOptimizeForNetworkUse = YES;
        //异步转码
        [exportSession exportAsynchronouslyWithCompletionHandler:^(void){
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            });
            
            switch (exportSession.status) {
                case AVAssetExportSessionStatusCancelled:
                    NSLog(@"AVAssetExportSessionStatusCancelled");
                    break;
                case AVAssetExportSessionStatusUnknown:
                    NSLog(@"AVAssetExportSessionStatusUnknown");
                    break;
                case AVAssetExportSessionStatusWaiting:
                    NSLog(@"AVAssetExportSessionStatusWaiting");
                    break;
                case AVAssetExportSessionStatusExporting:
                    NSLog(@"AVAssetExportSessionStatusExporting");
                    break;
                case AVAssetExportSessionStatusCompleted:
                {
                    //获取视频第一帧的图片
                    UIImage *image=[weakSelf.recordEngine movieToImageHandlerVideoURL:sourceUrl];
                    //获取视频路径
                    NSString *fileResultPath=[@"file://" stringByAppendingString:cachePath];
      
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        //删除tmp中的临时MOV文件
                        NSArray *tmpFiles=[fileManager contentsOfDirectoryAtPath:NSTemporaryDirectory() error:nil];
                        for (NSString *fileName in tmpFiles) {
                            if([fileName containsString:@".MOV"]){
                                [fileManager removeItemAtPath:[NSTemporaryDirectory() stringByAppendingPathComponent:fileName] error:nil];
                            }
                        }
                        NSLog(@"tmpFiles == %@",tmpFiles);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [MBProgressHUD showSuccess:@"转换完成" toView:weakSelf.view];
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                            if(weakSelf.delegate&&[weakSelf.delegate respondsToSelector:@selector(getMovieToImageHandler:videoFilePath:)]){
                                [weakSelf.delegate getMovieToImageHandler:image videoFilePath:fileResultPath];
                            }
                        });
                    });
                
                    break;
                }
                case AVAssetExportSessionStatusFailed:
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [MBProgressHUD showSuccess:@"转换失败" toView:weakSelf.view];
                    });
                    NSLog(@"AVAssetExportSessionStatusFailed");
                    break;
            }
        }];
    }
}

#pragma mark - WCLRecordEngineDelegate
- (void)recordProgress:(CGFloat)progress {
    if (progress >= 1) {
        [self recordAction:self.recordBt];
        self.allowRecord = NO;
    }
    self.progressView.progress = progress;
}

#pragma mark - 各种点击事件
//返回点击事件
- (IBAction)dismissAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

//开关闪光灯
 - (IBAction)flashLightAction:(id)sender {
    if (self.changeCameraBT.selected == NO) {
        self.flashLightBT.selected = !self.flashLightBT.selected;
        if (self.flashLightBT.selected == YES) {
            [self.recordEngine openFlashLight];
        }else {
            [self.recordEngine closeFlashLight];
        }
    }
}

#pragma mark - 切换前后摄像头
- (IBAction)changeCameraAction:(id)sender {
    self.changeCameraBT.selected = !self.changeCameraBT.selected;
    if (self.changeCameraBT.selected == YES) {
        //前置摄像头
        [self.recordEngine closeFlashLight];
        self.flashLightBT.selected = NO;
        [self.recordEngine changeCameraInputDeviceisFront:YES];
    }else {
        [self.recordEngine changeCameraInputDeviceisFront:NO];
    }
}
#pragma mark - 保存视频后的操作
- (IBAction)recordNextAction:(id)sender {
    if (_recordEngine.videoPath.length > 0) {
        __weak typeof(self) weakSelf = self;
        [MBProgressHUD showMessag:@"正在保存视频" toView:self.view];
        //movieImage:第一帧截图 moviePath:录制视频文件地址
        [self.recordEngine stopCaptureHandler:^(UIImage *movieImage, NSString *moviePath) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.locationVideoBT.alpha = 1;
                self.recordBt.selected=NO;
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                [MBProgressHUD showSuccess:@"保存成功" toView:weakSelf.view];
                NSString *fileResultPath=[@"file://" stringByAppendingString:moviePath];
                //转码成MP4
               [self convertMovSourceURL:[NSURL URLWithString:fileResultPath]];
               NSLog(@"moviePath == %@",[NSURL URLWithString:fileResultPath]);
            });
        }];
    }else {
        [MBProgressHUD showSuccess:@"请先录制视频~" toView:self.view];
    }
}
#pragma mark - 本地视频点击视频
- (IBAction)locationVideoAction:(id)sender {
    self.videoStyle = VideoLocation;
    [self.recordEngine shutdown];
    [self presentViewController:self.moviePicker animated:YES completion:nil];
}

#pragma mark - 开始和暂停录制事件
- (IBAction)recordAction:(UIButton *)sender {
    self.defImageUserBgView.hidden=YES;
    if (self.allowRecord) {
        self.videoStyle = VideoRecord;
        self.recordBt.selected = !self.recordBt.selected;
        if (self.recordBt.selected) {
            if (self.recordEngine.isCapturing) {
                [self.recordEngine resumeCapture];
            }else {
                [self.recordEngine startCapture];
            }
            [MBProgressHUD showSuccess:@"开始录制视频" toView:self.view];
        }else {
            [MBProgressHUD showSuccess:@"已暂停录制" toView:self.view];
            [self.recordEngine pauseCapture];
        }
        [self adjustViewFrame];
    }
}


@end
